//
//  GroupShoppingDetailViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/3/26.
//  Copyright © 2016年 yuf. All rights reserved.
//
#import <QuartzCore/QuartzCore.h>
#import "GroupShoppingDetailViewController.h"
#import "AllMovieCommentViewController.h"
#import "FoodsMenuTableViewCell.h"
#import "SureGroupIndentViewController.h"
#import "MovieCommentTableViewCell.h"
#import "SharePopView.h"
#import "GraphicDetailsViewController.h"
#define DegreesToRadians(degrees) (degrees * M_PI / 180)
static NSString * cellIndentfier = @"FoodsMenuTableViewCell";
static NSString *CellIdentify = @"MovieCommentTableViewCell";
@interface GroupShoppingDetailViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIScrollView *scroView;
@property (weak, nonatomic) IBOutlet UIButton *collectButton;
@property (strong, nonatomic) IBOutlet MTreeView *treeView;
@property (weak, nonatomic) IBOutlet UITableView *evaluationTableView;//评价TableView
@property (weak, nonatomic) IBOutlet UIView *commentView;
@property (weak, nonatomic) IBOutlet UILabel *commentNumber;
@property (weak, nonatomic) IBOutlet UILabel *commentScore;
@property(nonatomic,strong)NSMutableArray * commitArray;
@property(nonatomic,strong)NSMutableArray * heightArray;

@property (weak, nonatomic) IBOutlet UIButton *moreCommentButton;

@property (strong, nonatomic) IBOutlet UIView *haveToKnowView; //购买须知
@property (weak, nonatomic) IBOutlet UILabel *userKnowRule;

@property (strong, nonatomic) IBOutlet UILabel *functionTime;

@property (strong, nonatomic) IBOutlet UILabel *usefulTime;

@property(nonatomic,strong)NSArray * shoppingListArray;//套餐详情

@property (strong, nonatomic) IBOutlet UIImageView *shopImage;
@property (strong, nonatomic) IBOutlet UILabel *shopName;
@property (strong, nonatomic) IBOutlet UILabel *shopInfo;
@property (strong, nonatomic) IBOutlet UILabel *shopPrice;
@property (strong, nonatomic) IBOutlet UILabel *shopSoldNum;
@property (strong, nonatomic) IBOutlet UILabel *shopScore;
@property (strong, nonatomic) IBOutlet UILabel *shopCommentNumber;
@property (strong, nonatomic) IBOutlet UILabel *shopSecondName;
@property (strong, nonatomic) IBOutlet UILabel *shopAddress;
@property (strong, nonatomic) IBOutlet UILabel *shopPhone;

@property(nonatomic,strong)NSDictionary * shopInfoDic;



@end

@implementation GroupShoppingDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _heightArray = [NSMutableArray array];
    _commitArray = [NSMutableArray array];
    [self initViewLayout];
    [self getShoppingDetail];
    [self getShoppingDetailList];
    [self haveToKnow];
    [self getServiceInfo];
    [self getComments];
    [self ifCollected];
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroView];
    [self adaptiveViewLayout:self.commentView];
    [self adaptiveViewLayout:self.haveToKnowView];
    
    self.treeView.rowHeight = 60.0f;
    [self.treeView registerNib:[UINib nibWithNibName:cellIndentfier bundle:nil] forCellReuseIdentifier:cellIndentfier];
    [self.evaluationTableView registerNib:[UINib nibWithNibName:CellIdentify bundle:nil] forCellReuseIdentifier:CellIdentify];
    self.evaluationTableView.delegate = self;
    self.evaluationTableView.dataSource = self;
    self.treeView.rootNode = [MTreeNode initWithParent:nil expand:NO];
    
    _scroView.contentSize = flexibleSize(CGSizeMake(0, 967), NO);
    
}
#pragma mark == 返回
- (IBAction)back:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}

#pragma mark ==== 团购评论列表
- (void)getComments{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_groupShoppingId forKey:@"mgpdId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryAppMallGrouponComment withHttpType:@"POST" withTag:SX_SX_queryAppMallGrouponComment];
}

#pragma mark == 查询团购详情
- (void)getShoppingDetail{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_groupShoppingId forKey:@"mgpdId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryGrouponStoreInfo withHttpType:@"POST" withTag:SX_SX_queryGrouponStoreInfo];
}

#pragma mark ====查询商家是否收藏
- (void)ifCollected{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_goodsStoreId forKey:@"storeId"];
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryStoreIsCollect withHttpType:@"POST" withTag:SX_SX_queryStoreIsCollect];
    
}

#pragma mark == 查询套餐详情
- (void)getShoppingDetailList{
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_groupShoppingId forKey:@"mgpdId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryGrouponPackDetype withHttpType:@"POST" withTag:SX_SX_queryGrouponPackDetype];
}
#pragma mark == 查询购买须知
- (void)haveToKnow{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_groupShoppingId forKey:@"mgpdId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryAppBuyNotes withHttpType:@"POST" withTag:SX_SX_queryAppBuyNotes];
}


#pragma mark == 查询是否随时退  免预约
- (void)getServiceInfo{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:_groupShoppingId forKey:@"projectId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryAppGroupBuyingRules withHttpType:@"POST" withTag:SX_SX_queryAppGroupBuyingRules];
}

#pragma mark === 收藏
- (IBAction)collectHandel:(id)sender {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"addGoodsCollectInfo" forKey:@"method"];
    [dic setObject:@"2" forKey:@"collectType"];
    [dic setObject:_goodsStoreId forKey:@"goodsId"];
    [dic setObject:@"2" forKey:@"storeType"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_AddGoodsCollectInfo withHttpType:@"POST" withTag:SX_AddGoodsCollectInfoTag];
}

#pragma mark == 分享
- (IBAction)shareHandel:(id)sender {
    SharePopView * popView = [[SharePopView alloc]initWithTitles:@[@"微信好友",@"朋友圈",@"新浪微博",@"QQ好友"] complect:^(NSInteger index) {
        switch (index) {
            case 0:
            {
                [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatSession] content:@"" image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
                    if (response.responseCode == UMSResponseCodeSuccess) {
                        //            NSLog(@"分享成功！");
                    }
                }];
                
            }
                break;
            case 1:
            {
                [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatTimeline] content:@"" image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
                    if (response.responseCode == UMSResponseCodeSuccess) {
                        //            NSLog(@"分享成功！");
                    }
                }];
            }
                break;
            case 2:
            {
                [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToSina] content:@"" image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
                    if (response.responseCode == UMSResponseCodeSuccess) {
                        //            NSLog(@"分享成功！");
                    }
                }];
            }
                break;
            case 3:
            {
                [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToQQ] content:@"" image:nil location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
                    if (response.responseCode == UMSResponseCodeSuccess) {
                        //            NSLog(@"分享成功！");
                    }
                }];
            }
                break;
            default:
                break;
        }

    }];
    [popView show];
}

#pragma mark == 更多评论
- (IBAction)commentshandel:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    AllMovieCommentViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"AllMovieComment"];
    page.type = 2;
    page.commentId = _groupShoppingId;
    [self.navigationController   pushViewController:page animated:YES];
}

#pragma mark  == 地图
- (IBAction)addressHandel:(id)sender {
}

#pragma mark  == 图文详情
- (IBAction)shopListDetail:(id)sender {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    GraphicDetailsViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"GraphicDetails"];
//    page.
    [self.navigationController   pushViewController:page animated:YES];
    
}

#pragma mark  == 拨打电话
- (IBAction)callStorePhone:(UIButton *)sender {
     [Common callPhone:_shopPhone.text view:sender];
}

#pragma mark == 立即购买
- (IBAction)buyNow:(id)sender {
  
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    SureGroupIndentViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"SureGroupIndent"];
    page.groupShoppingId = _groupShoppingId;
    page.shopInfoDic = _shopInfoDic;
    [self.navigationController   pushViewController:page animated:YES];
    
}

#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView == _evaluationTableView) {
        return 1;
    } else {
        return [_treeView numberOfSectionsInTreeView:_treeView];
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView == _evaluationTableView) {
        if (_commitArray.count<=2) {
            return _commitArray.count;
        }else{
            return 2;
        }
    } else {
        return [_treeView treeView:_treeView numberOfRowsInSection:section];
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView == self.treeView) {
        return 30*VerticalRatio();
    } else {
        return 0;
    }
}
    
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (tableView == self.treeView) {
        MTreeNode *subNode = [[self.treeView.rootNode subNodes] objectAtIndex:section];
        NSDictionary *nodeData = subNode.content;
        UIView *sectionView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetMaxX(self.view.bounds), 30*VerticalRatio())];
        
        {
            sectionView.tag = 1000 + section;
            UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(sectionTaped:)];
            [sectionView addGestureRecognizer:recognizer];
            sectionView.backgroundColor = kGetColor(237, 237, 237);
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 29*VerticalRatio(), CGRectGetMaxX(self.view.bounds), 1)];
            line.backgroundColor = kGetColor(229, 229, 229);
            [sectionView addSubview:line];
        }
        {
            //        UIImageView *tipImageView = [[UIImageView alloc] initWithFrame:CGRectMake(17, 20, 8, 10)];
            //        tipImageView.image = [UIImage imageNamed:@"tip"];
            //        tipImageView.tag = 10;
            //        [sectionView addSubview:tipImageView];
            //        [self doTipImageView:tipImageView expand:subNode.expand];
        }
        {
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, CGRectGetMaxX(self.view.bounds), 30*VerticalRatio())];
            label.font = [UIFont systemFontOfSize:15.0f];
            label.textAlignment = NSTextAlignmentCenter;
            label.tag = 20;
            label.text = nodeData[@"mgpdTypeName"];
            [sectionView addSubview:label];
        }
        return sectionView;
    } else {
        return nil;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _evaluationTableView) {
        CGFloat height= [_heightArray[indexPath.row] floatValue]*VerticalRatio();
        return height ;
    } else {
        return 30*VerticalRatio();
    }
    
    
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == _evaluationTableView) {
        MovieCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentify ];
        if (cell == nil) {
            cell = [[MovieCommentTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentify];
        }
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        for (UIView *view in cell.subviews) {
            if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
                [view removeFromSuperview];
            }
        }
        NSDictionary * dic = _commitArray[indexPath.row];
        NSString * image = dic[@"memberImg"];
        if (image) {
            [cell.headImage sd_setImageWithURL:[NSURL URLWithString:image]];
        }else{
            cell.headImage.image = [UIImage imageNamed:@"comment1"];
        }
        double star = [[NSString stringWithFormat:@"%.1f",[dic[@"mgcoCommentStars"]floatValue ]/2]doubleValue];
        
        CommitStarsView * stars = [[CommitStarsView alloc]initWithFrame:flexibleFrame(CGRectMake(13, 50, 80, 15), NO) Stars:star];
        [cell addSubview:stars];
        
        cell.commentInfo.frame = flexibleFrame(CGRectMake(10, 72, 300, 15), YES);
        cell.commentInfo.numberOfLines = 0;
        cell.commentInfo.text = dic[@"mgcoContent"];
        [cell.commentInfo sizeToFit];
        
        cell.name.text = dic[@"mgcoAuthor"];
        
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        [formatter setDateFormat:@"yyyy-MM-dd HH:MM:ss"];
        NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:[dic[@"commentDate"] integerValue]/1000];
        cell.date.text = [formatter stringFromDate:confromTimesp];
        //
        
        return cell;
    } else {
        FoodsMenuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentfier];
        if (cell == nil) {
            cell= [[FoodsMenuTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentfier];
            
        }
        
        for (UIView *view in cell.subviews) {
            if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
                [view removeFromSuperview];
            }
        }
        MTreeNode *subNode = [self.treeView nodeAtIndexPath:indexPath];
        NSDictionary *dic = subNode.content;
        cell.foodsName.text = dic[@"mgpdName"];
        cell.foodsPrice.text = [NSString stringWithFormat:@"¥%@",dic[@"mgpdUnitPrice"]];
        cell.foodsNumber.text = [NSString stringWithFormat:@"%@%@",dic[@"mgpdNum"],dic[@"mgpdUnit"]];
        return cell;
    }
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [self.treeView expandNodeAtIndexPath:indexPath];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}

#pragma mark Action

- (void) doTipImageView:(UIImageView *)imageView expand:(BOOL) expand {
    [UIView animateWithDuration:0.2f animations:^{
        imageView.transform = (expand) ? CGAffineTransformMakeRotation(DegreesToRadians(90)) : CGAffineTransformIdentity;
    }];
}

- (void)sectionTaped:(UIGestureRecognizer *) recognizer {
    UIView *view = recognizer.view;
    NSUInteger tag = view.tag - 1000;
    UIImageView *tipImageView = [view viewWithTag:10];
    MTreeNode *subNode = [self.treeView nodeAtIndexPath:[NSIndexPath indexPathForRow:-1 inSection:tag]];
    [self.treeView expandNodeAtIndexPath:[NSIndexPath indexPathForRow:-1 inSection:tag]];
    [self doTipImageView:tipImageView expand:subNode.expand];
    
    NSInteger height = 0;
    if(subNode.expand){
        height = 30*[_treeView treeView:_treeView numberOfRowsInSection:tag]*VerticalRatio();
        _treeView.frame = CGRectMake(0, 263*VerticalRatio(), 320*VerticalRatio(), _treeView.frame.size.height+height);
    }else{
        NSMutableArray *arr = _shoppingListArray[tag][@"list"];
        height = 30*arr.count*VerticalRatio();
        _treeView.frame = CGRectMake(0, 263*VerticalRatio(), 320*VerticalRatio(), _treeView.frame.size.height-height);
    }
    
    _haveToKnowView.frame = CGRectMake(0, CGRectGetMaxY(_treeView.frame), 320*VerticalRatio(), CGRectGetHeight(_haveToKnowView.frame));
    _scroView.contentSize = CGSizeMake(0, CGRectGetMaxY(_haveToKnowView.frame));
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    if (tag == SX_SX_queryGrouponPackDetype){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _shoppingListArray = database[@"result"];
            NSInteger height = 0;
            for (NSUInteger i = 0; i < [_shoppingListArray count]; i++) {
                MTreeNode *node = [MTreeNode initWithParent:self.treeView.rootNode expand:NO];
                
                NSMutableArray *arr = _shoppingListArray[i][@"list"];
                for (int j = 0; j < arr.count; j++) {
                    MTreeNode *subnode = [MTreeNode initWithParent:node expand:NO];
                    subnode.content = arr[j];
                    [node.subNodes addObject:subnode];
                    height += 30;
                }
                node.content = _shoppingListArray[i];
                [self.treeView.rootNode.subNodes addObject:node];
                height += 30;
            }
            _treeView.frame = flexibleFrame(CGRectMake(0, 263, 320, height), NO);
            _haveToKnowView.frame = CGRectMake(0, CGRectGetMaxY(_treeView.frame), 320*VerticalRatio(), CGRectGetHeight(_haveToKnowView.frame));
            _scroView.contentSize = CGSizeMake(0, CGRectGetMaxY(_haveToKnowView.frame));

            _treeView.delegate = self;
            _treeView.dataSource = self;
            _treeView.treeViewDelegate = self;
            [_treeView reloadData];
            //展开cell
            for (int j = 0; j < _shoppingListArray.count; j++) {
                [self.treeView expandNodeAtIndexPath:[NSIndexPath indexPathForRow:-1 inSection:j]];
            }
            
        }
        
    }else if (tag == SX_SX_queryGrouponStoreInfo){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            
            NSDictionary * dic = database[@"result"];
            _shopInfoDic = dic;
            //        NSString * image = dic[@"storeImg"];
            //        if (image) {
            //            [cell.shoppingImage sd_setImageWithURL:[NSURL URLWithString:image]];
            //        }else{
            //            cell.shoppingImage.image = [UIImage imageNamed:@"gsInfo1"];
            //        }
            _shopName.text = dic[@"storeName"];
            _shopInfo.text = [NSString stringWithFormat:@"%ld人餐，节假日通用！",[[Common stringFromData:dic[@"mgmnNumber"]] integerValue]];
            NSString * price = [NSString stringWithFormat:@"¥%.2f",[dic[@"mgpiGourponAmount"] floatValue]];
            NSString * oldPrice = [NSString stringWithFormat:@"门市价:¥%@",dic[@"mgpiOrginalAmount"]];
        NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@  %@",price,oldPrice]];
            [str addAttribute:NSForegroundColorAttributeName value:kGetColor(240, 59, 59) range:NSMakeRange(0, price.length)];
            [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20*VerticalTexeRatio()] range:NSMakeRange(1, price.length-1)];
            _shopPrice.attributedText = str;
            
            _shopSoldNum.text = [NSString stringWithFormat:@"已售%@",dic[@"mgprSelledCount"]];
            _shopScore.text = [NSString stringWithFormat:@"%.1f分",[dic[@"mgprComm"] floatValue]/2];
            _shopCommentNumber.text = [NSString stringWithFormat:@"%@人评论",dic[@"mgprNum"]];
            _shopSecondName.text = dic[@"storeName"];
            _shopAddress.text = dic[@"storeAddress"];
            _shopPhone.text = dic[@"storePhone"];
            [_shopImage sd_setImageWithURL:[NSURL URLWithString:dic[@"storeImg"]] completed:nil];

        }
    }else if (tag == SX_SX_queryAppBuyNotes){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            NSDictionary * dic = database[@"result"];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateStyle:NSDateFormatterMediumStyle];
            [formatter setTimeStyle:NSDateFormatterShortStyle];
            [formatter setDateFormat:@"yyyy.MM.dd"];
            if(![dic[@"mgprAddDate"] isEqual:[NSNull null]]){
                NSDate *start = [NSDate dateWithTimeIntervalSince1970:[dic[@"mgprAddDate"] integerValue]/1000];
                if(![dic[@"mgvaValidityDate"] isEqual:[NSNull null]]){
                    NSDate *end = [NSDate dateWithTimeIntervalSince1970:[dic[@"mgvaValidityDate"] integerValue]/1000];
                    _functionTime.text = [NSString stringWithFormat:@"%@-%@",[formatter stringFromDate:start],[formatter stringFromDate:end]];
                }
                [formatter setDateFormat:@"HH"];
                NSDate *startH = [NSDate dateWithTimeIntervalSince1970:[dic[@"mguaBeginHour"] integerValue]/1000];
                NSDate *endH = [NSDate dateWithTimeIntervalSince1970:[dic[@"mguaEndHour"] integerValue]/1000];
                NSString * startHour = [formatter stringFromDate:startH];
                NSString * endHour = [formatter stringFromDate:endH];
                
                [formatter setDateFormat:@"MM"];
                NSDate *startM = [NSDate dateWithTimeIntervalSince1970:[dic[@"mguaBeginMinute"] integerValue]/1000];
                NSDate *endM = [NSDate dateWithTimeIntervalSince1970:[dic[@"mguaEndMinute"] integerValue]/1000];
                NSString * startMin = [formatter stringFromDate:startM];
                NSString * endMin = [formatter stringFromDate:endM];
                
                _usefulTime.text = [NSString stringWithFormat:@"%@:%@-%@:%@",startHour,startMin,endHour,endMin];
            }else{
                
            }
            _userKnowRule.text = dic[@"mgaiContent"];
            
//            NSLog(@"%@",dic[@"mgaiContent"]);
        }
    
    }else if (tag == SX_SX_queryAppGroupBuyingRules){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            NSMutableArray * nameArray = [NSMutableArray array];
            NSDictionary * dic = database[@"result"];

            if ([[NSString stringWithFormat:@"%@",dic[@"mgreIsDueRefund"]] isEqualToString:@"1"]) {
                [nameArray addObject:@" 随时退"];
            }
            

            if ([[NSString stringWithFormat:@"%@",dic[@"mgreIsAnytimeRefund"]] isEqualToString:@"1"]) {

                [nameArray addObject:@" 过期退"];
            }
            

            if ([[NSString stringWithFormat:@"%@",dic[@"mgsnReservationType"]] isEqualToString:@"1"]) {

                [nameArray addObject:@" 免预约"];
            }else{
                [nameArray addObject:@" 需预约"];
            }
            
            for (int i = 0; i<nameArray.count; i++) {
                UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
                button.frame = flexibleFrame(CGRectMake(15+70*i, 202, 65, 22), YES);
                [button setTitle:nameArray[i] forState:UIControlStateNormal];
                [button setTitleColor:[UIColor colorWithRed:0.569 green:0.757 blue:0.153 alpha:1.000] forState:UIControlStateNormal];
                [button setImage:[UIImage imageNamed:@"groupShopDetail1"] forState:UIControlStateNormal];
                button.titleLabel.font = [UIFont systemFontOfSize:12*VerticalTexeRatio()];
                [_scroView addSubview:button];
            }
        }
    
    }else  if (tag == SX_SX_queryAppMallGrouponComment){
               if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
                   
                   [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
                   
               }else  {
                NSArray *arr = database[@"result"];

                   for (id entity in arr) {
                       [self.commitArray addObject:entity];
                   }
                   for (int i = 0; i<_commitArray.count; i++) {
                       NSString * commentImage = _commitArray[i][@"mgciImag"];
                       NSString * comment = _commitArray[i][@"mgcoContent"];
                       NSInteger height = 0;
                       if (commentImage.length==0 ) {
                           height = 90;
                       }else{
                           height = 130;
                       }
                       
                       
                       int lines = 0;
                       CGSize cSize = [comment sizeWithFont:[UIFont systemFontOfSize:14*VerticalTexeRatio()]];
                       lines = cSize.width/300*VerticalRatio() + 1 ;
                       
                       height  += lines * 17;
                       
                       [_heightArray addObject:@(height)];
                   }
                   NSString * coment = @"评价";
                   _commentNumber.text = [NSString stringWithFormat:@"%@(%ld)",coment,_commitArray.count];
                   
                   double start = [[NSString stringWithFormat:@"%.1f",[database[@"result"][@"commentStar"]floatValue]/2] doubleValue];
                   CommitStarsView * CommentStars = [[CommitStarsView alloc]initWithFrame:flexibleFrame(CGRectMake(197, 783, 65, 15), NO) SmallStars:start];
                   [_scroView addSubview:CommentStars];
                   _commentScore.text = [NSString stringWithFormat:@"%.1f分",start];
                   
                   _moreCommentButton.layer.borderColor = kGetColor(244, 244, 244).CGColor;
                   _moreCommentButton.layer.borderWidth = 1;
                   NSMutableAttributedString * str = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"查看全部%ld评价",_commitArray.count]];
                   // 创建图片图片附件
                   NSTextAttachment *attach = [[NSTextAttachment alloc] init];
                   attach.image = [UIImage imageNamed:@"Business details3"];
                   attach.bounds = flexibleFrame(CGRectMake(1, -1, 6, 10), NO);
                   NSAttributedString *attachString = [NSAttributedString attributedStringWithAttachment:attach];
                   [str appendAttributedString:attachString];
                   [_moreCommentButton setAttributedTitle:str forState:UIControlStateNormal];
                   
                   if (_heightArray.count>0) {
                       
                   NSInteger rows = _heightArray.count;
                   if (_heightArray.count>2) {
                       rows = 2;
                   }
                   CGFloat Height = 0;
                   for (int i = 0; i<rows; i++) {
                       CGFloat height = [_heightArray[i]floatValue];
                       Height = Height+height;
                   }
                   _evaluationTableView.frame = flexibleFrame(CGRectMake(0, 40, 320, Height), NO);
                   _moreCommentButton.frame = flexibleFrame(CGRectMake(-1, CGRectGetMaxY(_evaluationTableView.frame)/VerticalRatio(), 322, CGRectGetHeight(_moreCommentButton.frame)/VerticalRatio()), NO);
                       _commentView.frame = flexibleFrame(CGRectMake(0, CGRectGetMinY(_commentView.frame)/VerticalRatio(), 320, Height+40+36), NO);
                       _scroView.contentSize = CGSizeMake(0, CGRectGetMaxY(_commentView.frame)+1);
                   
                   _evaluationTableView.delegate = self;
                   _evaluationTableView.dataSource = self;
                   [_evaluationTableView reloadData];
                   }else{
                       _commentView.frame = flexibleFrame(CGRectMake(0, CGRectGetMinY(_commentView.frame)/VerticalRatio(), 320, 5), NO);
                       [_commentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
                       UIView * line = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 5), NO)];
                       line.backgroundColor = kGetColor(244, 244, 244);
                       [_commentView addSubview:line];
                       
                       _evaluationTableView.frame = flexibleFrame(CGRectMake(0, CGRectGetMinY(_commentView.frame)/VerticalRatio()+5, 320, CGRectGetHeight(_evaluationTableView.frame)/VerticalRatio()), NO);
                       _scroView.contentSize = CGSizeMake(0, CGRectGetMaxY(_evaluationTableView.frame)+1);
                   }
            }
               
    }else if (tag == SX_AddGoodsCollectInfoTag){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            _collectButton.selected = !_collectButton.selected;
        }
    }else if (tag == SX_SX_queryStoreIsCollect){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            NSString * status = database[@"result"];
            if ([status isEqualToString:@"1"]) {
                _collectButton.selected = YES;
            }else{
                _collectButton.selected = NO;
            }
        }
        
    }

}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
